package swu.cx.okhttptest

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader


class MainActivity : AppCompatActivity() {
    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       // getAsynchronous()
        //getWay()
       //downLoadFile()
        realUpload()
        //postData()
        //fileTest()
    }
    fun getWay(){
        Thread {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://192.168.0.103/a.php")
                .build()
            val response = client.newCall(request).execute()
            //接收返回结果
            val result = response.body?.string()
            Log.v("cx","结果为：$result")
        }.start()
    }
    fun getAsynchronous(){
        val client = OkHttpClient()
        val request = Request.Builder()
            .url("http://192.168.0.103/a.php")
            .build()
        val response = client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                //请求失败的处理
                Log.v("cx","网络异常，请换5G网！")
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body?.string()
                hello.text = result
                Log.v("cx","结果为：$result")
            }

        })
    }
    fun postData(){
        val client = OkHttpClient()
        val requestBody = FormBody.Builder()
            .add("user_name", "jack")
            .add("user_pwd", "123")
            .build()
        val request = Request.Builder()
                .url("http://192.168.0.103//login/login.php")
                .post(requestBody)
                .build()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.v("cx","网络异常，请稍后再试！")
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body?.string()
                Log.v("cx", "结果为：$result")
                //Log->结果为：登录成功
            }
        })
    }
    fun realUpload(){
        val filePath = Environment.getExternalStorageDirectory().absolutePath+"/a/a.mp4"
        val file = File(filePath)
        Thread{
            if (Build.VERSION.SDK_INT >= 23) {
                val REQUEST_CODE_CONTACT = 101
                val permissions = arrayOf<String>(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                //验证是否许可权限
                for (str in permissions) {
                    if (this.checkSelfPermission(str) !== PackageManager.PERMISSION_GRANTED) {
                        //申请权限
                        this.requestPermissions(permissions, REQUEST_CODE_CONTACT)
                        return@Thread
                    } else {
                        upLoadFile(file)
                    }
                }
            }
        }.start()
    }
    fun fileTest(){
        val filePath = Environment.getExternalStorageDirectory().absolutePath+"/a.jpg"
        val file = File(filePath)
        val isExists = file.exists()
        Log.v("cx","文件是否存在：$isExists--文件路径：${file.absolutePath}")
    }
    private fun upLoadFile(file: File){
        val url = "http://192.168.0.103/upload.php"
        val client = OkHttpClient()
//        "application/octet-stream".toMediaTypeOrNull()
//        file.asRequestBody("image/jpg".toMediaTypeOrNull())
        val requestBody = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", "这就是Okhttp吗！.mp4",file.asRequestBody("video/mp4".toMediaTypeOrNull()))
            .build()
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()
        client.newCall(request).execute()
    }
    private fun downLoadFile(){
        val url = "http://192.168.0.103/这就是Okhttp吗！.mp4"
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.v("cx","下载失败！")
            }

            override fun onResponse(call: Call, response: Response) {
                val content = response.body?.byteStream().use {
                    it?.readBytes()
                }
                val filePath = Environment.getExternalStorageDirectory().absolutePath+"/a/这就是Okhttp吗！.mp4"
                val file = File(filePath)
                if (!file.exists()){
                    file.createNewFile()
                }
                file.outputStream().use {
                    it.write(content)
                }
            }

        })
    }
}